package com.htd.erp.common;

import java.io.Serializable;

import javax.enterprise.context.Conversation;
import javax.enterprise.inject.Instance;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.htd.erp.model.AbstractEntity;

public abstract class EntityHome<T extends AbstractEntity> implements Serializable {

	private static final long serialVersionUID = -5442642050755059918L;
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	protected Long id;
	
	protected T entity;
	
	@Inject
    private Conversation conversation;
	
	@Inject
	private Instance<Repository> genericRepository;

	public EntityHome() {
		this.entity = newEntityInstance();
	}
	
	abstract protected Class<T> getEntityClass();
	
	abstract protected T newEntityInstance();
	
	public void postConstruct() {
		if(!FacesContext.getCurrentInstance().isPostback()) {
			if(id != null && id.intValue() > 0) {
				entity = getRepository().findById(getEntityClass(), id);
			}
			startConversation();
		}
	}

	public void save() {
		entity = getEntity().isNew()? getRepository().create(getEntity()) : getRepository().update(getEntity());
		logger.info("{} (id:{}) is saved.", entity.getClass().getSimpleName(), entity.getId());
		entity = newEntityInstance();
	}

	public void delete(Long entityId) {
		getRepository().delete(getEntityClass(), entityId);
		entity = newEntityInstance();
	}
	
	protected void startConversation() {
		if (conversation.isTransient()) {
		    conversation.begin();
		}
	}
	
	protected void stopConversation() {
		if (!conversation.isTransient()) {
			conversation.end();
		}
	}

	public T getEntity() {
		return entity;
	}
	
	public void setEntity(T entity) {
		this.entity = entity;
	}
	
	public void setId(Long id) {
		this.id = id;
	}

	public Long getId() {
		return id;
	}
	
	// override point
	protected Repository getRepository() {
		return genericRepository.get();
	}
}
